package com.yy.micro.magic.data.resource;

import com.yy.micro.magic.data.domain.CodeItemVo;
import com.yy.micro.magic.data.domain.CodeMapVo;
import com.yy.micro.magic.data.entity.CodeMapEntity;
import com.yy.micro.magic.data.entity.CodeMapItemEntity;
import com.yy.micro.magic.data.repository.CodeItemRepository;
import com.yy.micro.magic.data.repository.CodeMapRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class CodeMapResource {

    @Autowired
    private CodeMapRepository codeMapRepository;
    @Autowired
    private CodeItemRepository codeItemRepository;

    public CodeMapVo saveOrUpdate(CodeMapVo vo){
        List<CodeItemVo> items = vo.getItems();
        if (!CollectionUtils.isEmpty(items)){
            items.forEach(i->{
                codeItemRepository.save(i.to());
            });
        }
        CodeMapEntity entity=codeMapRepository.save(vo.to());
        return CodeMapVo.create().from(entity);
    }

    public CodeMapVo load(String codeName){
        CodeMapEntity entity=codeMapRepository.findByCodeNameAndDisable(codeName,false);
        if (null != entity){
            CodeMapVo vo = CodeMapVo.create().from(entity);
            List<CodeMapItemEntity> items =codeItemRepository.findByCodeIdAndDisable(vo.getCodeId(),false);
            List<CodeItemVo> vos=items.stream().map(i->CodeItemVo.create().from(i)).collect(Collectors.toList());
            vo.setItems(vos);
            return vo;
        }
        return null;
    }

}
